package com.wg.msshopcar.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wg.msshopcar.entity.ShopCar;
import com.wg.msshopcar.entity.dto.ShopCarDTO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface ShopCarMapper extends BaseMapper<ShopCar> {
    /**
     * 根据用户ID查询购物车详情（仅关联必要表，直接使用shopcar.sku作为规格）
     */
    @Select("SELECT " +
            "  sc.id AS id, " +                  // 购物车记录ID
            "  sc.count, " +                     // 购买数量
            "  sc.selected, " +                  // 是否选中（如果有的话）
            "  sc.price, " +                     // 单价
            "  sc.product_id AS productId, " +   // 商品ID
            "  p.name AS productName, " +        // 商品名称
            "  p.main_img AS productImage, " +   // 商品主图
            "  sc.shop_id AS shopId, " +         // 店铺ID
            "  s.shop_name AS shopName, " +      // 店铺名称
            "  sc.sku AS sku " +            // 直接使用sku字段作为规格信息
            "FROM shopcar sc " +
            "LEFT JOIN product p ON sc.product_id = p.id " +  // 关联商品表拿名称和图片
            "LEFT JOIN shop s ON sc.shop_id = s.id " +        // 关联店铺表拿名称
            "WHERE sc.user_id = #{userId} " +
            "ORDER BY sc.time DESC")  // 按加入时间排序
    List<ShopCarDTO> selectCartDetailsByUserId(@Param("userId") Integer userId);

    /**
     * 结算时查询数据（同样简化）
     */
    @Select("<script>" +
            "SELECT " +
            "  sc.id AS id, " +
            "  sc.user_id AS userId, " +
            "  sc.product_id AS productId, " +
            "  p.name AS productName, " +
            "  sc.price, " +
            "  sc.count, " +
            "  sc.shop_id AS shopId, " +
            "  s.shop_name AS shopName, " +
            "  sc.sku AS sku, " +  // 规格信息直接用sku
            "  p.main_img AS productImage " +
            "FROM shopcar sc " +
            "LEFT JOIN product p ON sc.product_id = p.id " +
            "LEFT JOIN shop s ON sc.shop_id = s.id " +
            "WHERE sc.id IN " +
            "  <foreach collection='cartIds' item='id' open='(' separator=',' close=')'>" +
            "    #{id}" +
            "  </foreach>" +
            "ORDER BY sc.shop_id, sc.id" +
            "</script>")
    List<ShopCarDTO> selectCheckoutDataByCartIds(@Param("cartIds") List<Integer> cartIds);

}